package com.da.springboot.controller;

import com.da.springboot.dao.DepartmentDao;
import com.da.springboot.dao.EmployeeDao;
import com.da.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    //员工显示页面
    @GetMapping("/emps")
    public String list(Model model) {
        model.addAttribute("emps", employeeDao.getAll());
        return "emp/list";
    }

    //员工添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        model.addAttribute("depts", departmentDao.getDepartments());
        return "emp/add";
    }

    //添加员工
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        System.out.println("保存的员工信息是：" + employee);
        employeeDao.save(employee);
        //forward 转发
        //redirect 重定向
        return "redirect:/emps";
    }

    //修改员工回显
    @GetMapping("/emp/{id}")
    public String editEmp(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);
        model.addAttribute("depts", departmentDao.getDepartments());
        return "emp/add";
    }

    //修改员工
    @PutMapping("/emp")
    public String editEmp2(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //删除员工
    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
